--[[
    事件处理器，用于和EventMgr直接交互
]] local Services = require "global.Services"
---@type EventMgr
local EventMgr = Services.EVENT_MGR

local M = {}

---@type table<event, table<number, function>>
local listeners = {}

function M.listen(event, func)
    if not listeners[event] then
        listeners[event] = {}
        EventMgr.listen(event)
    end

    table.insert(listeners[event], func)
end

function M.listenBatch(eventBatch)
    for eventName, func in pairs(eventBatch) do
        M.listen(eventName, func)
    end
end

function M.unlisten(event, func)
    if not listeners[event] then
        -- 没有监听
        return
    end

    local funcIdx
    for i = 1, #listeners[event] do
        if listeners[event][i] == func then
            funcIdx = i
            break
        end
    end

    if not funcIdx then
        return
    end

    table.remove(listeners[event], funcIdx)
    if table.empty(listeners[event]) then
        listeners[event] = nil
        EventMgr.unlisten(event)
    end
end

function M.unlistenBatch(eventBatch)
    for eventName, func in pairs(eventBatch) do
        M.unlisten(eventName, func)
    end
end

--- 清空事件的监听
---@param event string? 要清空的事件名，如果没有传，则清空所有事件的监听
function M.clearListener(event)
    if not event then
        -- 清空所有事件监听
        local allEvent = table.keys(listeners)
        listeners = {}
        EventMgr.unlistenBatch(allEvent)
        return
    end

    if not listeners[event] then
        -- 没有监听
        return
    end

    listeners[event] = nil
    EventMgr.unlisten(event)
end

--- 触发事件
function M.dispatch(event, ...)
    EventMgr.dispatch(event, ...)
end

function M.dispatchSync(event, ...)
    return EventMgr:dispatchSync(event, ...)
end

-- 接收到事件，进行处理
function M.receive(event, ...)
    if not listeners[event] then
        -- 没有监听
        GERR("接收到没有监听的事件:", event)
        return
    end

    for i = 1, #listeners[event] do
        listeners[event][i](...)
    end
end

return M
